﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using XuanFe.AppLaunch.Common;
using XuanFe.Database.DAL;
using XuanFe.Database.Model;

namespace XuanFe.AppLaunch
{
    public partial class PassengerDetailForm : DevExpress.XtraEditors.XtraForm
    {
        private string m_CustomerId;
        private List<IDTypeModel> lstIDType;
        private List<NationModel> lstNation;
        private List<ItemObject> lstSex;

        public PassengerDetailForm(string customerId, List<IDTypeModel> lstIDType, List<NationModel> lstNation)
        {
            InitializeComponent();

            this.m_CustomerId = customerId;
            this.lstIDType = lstIDType;
            this.lstNation = lstNation;
            this.lstSex = new List<ItemObject>();
            this.lstSex.AddRange(new ItemObject[] { new ItemObject("男", "M"), new ItemObject("女", "F") });
        }
        public PassengerModel Data { get; private set; }
        private void BuildAll()
        {
            this.cmbPassengerIDTypeId.Properties.Items.Clear();
            this.cmbPassengerIDTypeId.Properties.Items.AddRange(this.lstIDType);
            if (this.cmbPassengerIDTypeId.Properties.Items.Count != 0)
            {
                this.cmbPassengerIDTypeId.SelectedIndex = 0;
            }
            this.cmbPassengerNation.Properties.Items.Clear();
            this.cmbPassengerNation.Properties.Items.AddRange(this.lstNation);
            this.cmbPassengerNation.SelectedItem = this.lstNation.Find(t => { return string.Equals(t.Id, "CN"); });

            this.cmbPassengerSex.Properties.Items.Clear();
            this.cmbPassengerSex.Properties.Items.AddRange(this.lstSex);
            if (this.cmbPassengerSex.Properties.Items.Count != 0)
            {
                this.cmbPassengerSex.SelectedIndex = 0;
            }
        }
        private bool AppendRecord(PassengerModel model)
        {
            try
            {
                using (DbConnection conn = MySQLHelper.Instance.CreateConnection())
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                            conn.Open();

                        DbTransaction tran = conn.BeginTransaction();
                        try
                        {
                            PassengerDAL.Instance.Insert(tran, model);

                            tran.Commit();
                            return (true);
                        }
                        catch
                        {
                            tran.Rollback();
                            return (false);
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch
            {
                return (false);
            }
        }
        /// <summary>
        /// 记录是否已存在
        /// </summary>
        /// <param name="UrlCd"></param>
        /// <returns></returns>
        private bool RecordIsExist(PassengerModel model)
        {
            if (PassengerDAL.Instance.Exist(model))
                return (true);

            return (false);
        }
        private bool ValidityCheck()
        {
            this.errorProvider1.ClearErrors();
            string message = string.Empty;
            if (Global.Instance.MandatoryFieldEmpty(this.txtPassengerName, false, ref message))
            {
                this.errorProvider1.SetError(this.txtPassengerName, message);
                this.txtPassengerName.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtPassengerMobileNumber, false, ref message))
            {
                this.errorProvider1.SetError(this.txtPassengerMobileNumber, message);
                this.txtPassengerMobileNumber.Focus();
                return (false);
            }
            if (this.cmbPassengerIDTypeId.Properties.Items.Count == 0 && Global.Instance.MandatoryFieldEmpty(this.cmbPassengerIDTypeId, false, ref message))
            {
                this.errorProvider1.SetError(this.cmbPassengerIDTypeId, message);
                this.cmbPassengerIDTypeId.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtPassengerIDNumber, false, ref message))
            {
                this.errorProvider1.SetError(this.txtPassengerIDNumber, message);
                this.txtPassengerIDNumber.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.cmbPassengerNation, false, ref message))
            {
                this.errorProvider1.SetError(this.cmbPassengerNation, message);
                this.cmbPassengerNation.Focus();
                return (false);
            }
            return (true);
        }

        private void PassengerDetailForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.BuildAll();
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.ValidityCheck()) return;

                PassengerModel model = new PassengerModel()
                {
                    CustomerId = this.m_CustomerId,
                    PassengerId = Guid.NewGuid().ToString("N").ToUpper(),
                    PassengerName = this.txtPassengerName.Text.Trim(),
                    ChineseSpell = this.txtPassengerChineseSpell.Text.Trim(),
                    MobileNumber = this.txtPassengerMobileNumber.Text.Trim(),
                    IDTypeId = ((IDTypeModel)this.cmbPassengerIDTypeId.SelectedItem).Id,
                    IDNumber = this.txtPassengerIDNumber.Text.Trim(),
                    ExpiryDate = this.dtPassengerExpiryDate.DateTime,
                    LastModifiedStaffId = LoginInfo.Instance.StaffLogon.Staff.Id,
                    LastModifiedDate = DateTime.Now,
                    Birthday = this.dtPassengerBirthday.DateTime,
                    NationId = ((NationModel)this.cmbPassengerNation.SelectedItem).Id,
                    Sex = ((ItemObject)this.cmbPassengerSex.SelectedItem).Value
                };

                if (this.RecordIsExist(model)
                    && !Global.Instance.QueryDlg(string.Format("乘机人“{0}”已经存在了，是否真的要添加？ ", model.PassengerName)))
                {
                    this.errorProvider1.SetError(this.txtPassengerName, "该记录已存在！");
                    this.txtPassengerName.Focus();
                    return;
                }
                if (!this.AppendRecord(model))
                {
                    Global.Instance.ErrorDlg("保存失败");
                    return;
                }
                this.Data = model;
                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                this.DialogResult = DialogResult.Cancel;
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }
    }
}
